package info.jafe.common.task;

import info.jafe.common.task.runnable.Done;
import info.jafe.common.task.runnable.Job;

/**
 * Created by jafe chang on 2016/12/31.
 */

public class TaskBuilder {
    Job job;
    Done done;
    Runnable fail;
    Object[] params;

    TaskBuilder() {
    }

    public TaskBuilder done(Done done) {
        this.done = done;
        return this;
    }

    public TaskBuilder fail(Runnable fail) {
        this.fail = fail;
        return this;
    }

    public TaskBuilder with(Object... params) {
        this.params = params;
        return this;
    }

    public void start() {
        ManagedTask task = new ManagedTask() {
            @Override
            protected Object[] task(Object... params) {
                if (job != null) {
                    return job.run(params);
                } else {
                    return null;
                }
            }

            @Override
            protected void onSuccess() {
                if (done != null) {
                    done.onSuccess();
                }
            }

            @Override
            protected void onSuccess(Object[] results) {
                if (done != null) {
                    done.onSuccess(results);
                }
            }

            @Override
            protected void onFailed() {
                if (fail != null) {
                    fail.run();
                }
            }
        };
        TaskManager.execute(task);
    }
}
